<?php
namespace Admin\Controller;

use Think\Cache;
class AppUserController extends \Admin\Controller\AdminController
{
	/***
	 * 查询用户列表
	 * @author 刘新
	 */
	public function userList()
	{
		//查询条件
		if(I('condition', '', '/^1\d{10}$/')) {
			$where['mobile'] = I('condition');
		} else if(I('condition', '', '/^\d+$/')) {
			$where['id'] = I('condition');
		}

		$where['status'] = array('egt', 0);
		//查詢認證列表
		$detailWhere['social_no'] = array('egt', '');
		$userDetail = M("UserDetail")->where($detailWhere)->select();
		$userDetailList = array();
		if(is_array($userDetail)){
			foreach($userDetail as $key=>$val){
				$userDetailList[$val['user_id']] = 1;
			}
		}
		//获取银行卡认证信息
		$bankVerification = M("bankVerification");
		$banklist = $bankVerification->select();
		$userbank = array();
		if(is_array($banklist)){
			foreach($banklist as $key=>$val){
				$userbank[$val['user_id']] = $val['status'];
			}
		}
		//获取用户列表
		$list = $this->lists('User', $where);
		if($list) {
			foreach($list as $key => &$val) {
				$val['status_text'] = C('APP_USER')[$val['status']];
				if($val['bit_status'] & 256) $val['status_text'] = '已锁定';
				if($userbank[$val['user_id']] == '1'){
					$val['bankstatus'] = '认证成功';
				}elseif($userbank[$val['user_id']] == '2'){
					$val['bankstatus'] = '认证失败';
				}else{
					$val['bankstatus'] = '未认证';
				}

				$val['realname_auth'] = '未认证';
				if($userDetailList[$val['id']] == 1) {
					$val['realname_auth'] = '已认证';
				}
				
				$val['conforms_auth'] = '未认证';
				if($val['authentication'] == 1) {
					$val['conforms_auth'] = '已认证';
				}
			}
		}
		
		$this->assign('_list', $list);
		$this->display('list');
	}
	
	/**
	 * 解锁
	 * @author 刘新
	 */
	public function unlock()
	{
		$id = I('id', '', '/^\d+$/');
		!$id && $this->error('参数错误');
		
		if(IS_GET) {
			//查询用户信息
			$user = $this->returnOne('User', array('id' => $id));
			!$user && $this->error('用户查询失败');
			
			//判断是否被锁定
			if(!($user['bit_status'] & 256)) $this->error('该账号没有被锁定');
			$user['status_text'] = '锁定';
			$user['lock_time_format'] = date('Y-m-d H:i:s', $user['lock_time']);
			$period = global_config('unlock_interval_time');
			$period = ($period ? $period*3600 : 86400);
			$user['unlock_time_format'] = date('Y-m-d H:i:s', $user['lock_time'] + $period);
			
			//查询锁定信息
			$log = $this->returnOne('UserLog', array('mobile' => $user['mobile'], 'type' => 1), 'create_time desc', 'id,content');
			if($log) {
				$user['lock_content'] = $log['content'];
				$user['log_id'] = $log['id'];
			}
			
			//查询用户详细信息
			$userDetail = $this->returnOne('UserDetail', array('user_id' => $id));
			
			if($userDetail) {
				unset($userDetail['id']);
				$user =array_merge($user, $userDetail);
			}

			$this->assign('_title', '用户账号解锁');
			$this->assign('user', $user);
			$this->display('unlock');
		}
	
		//解锁
		$logId = I('log_id', '', '/^\d+$/');
		!$logId && $this->error('参数错误1');
		
		$content = I('content', '');
		!$content && $this->error('请输入解锁说明 ');
		
		$admin = session('user_auth');
		$data = array('id' => $id, 'log_id' => $logId, 'admin_id' =>$admin['uid'], 'admin_name' => $admin['username']);
		$data['content'] = $content;
		
		$res = D('User')->unlock($data);
		if($res['error'] !== 0) $this->error($res['info']);
		$this->success('解锁成功', U('AppUser/userList'));
	}
	
	/**
	 * 重置用户密码
	 * @author 刘新
	 */
	public function resetPwd()
	{
		$id = I('id', '', '/^\d+$/');
		!$id && $this->error('参数错误');
	
		if(IS_GET) {
			//查询用户信息
			$user = $this->returnOne('User', array('id' => $id));
			!$user && $this->error('用户查询失败');
			$user['status_text'] = C('APP_USER')[$user['status']];
			$this->assign('_title', '重置用户密码');
			$this->assign('user', $user);
			$this->display('reset_password');
		}
	
		//重置密码
		$realname = I('realname', '');
		!$realname && $this->error('请输入真实姓名 ');

		$content = I('content', '');
		!$content && $this->error('请输入重置密码说明 ');
		
		$admin = session('user_auth');
		$data = array('id' => $id, 'admin_id' =>$admin['uid'], 'admin_name' => $admin['username']);
		$data['content'] = $content;
		$data['realname'] = $realname;
		
		$res = D('User')->resetPwd($data);
		if($res['error'] !== 0) $this->error($res['info']);
		$this->success('重置成功', U('AppUser/userList'));
	}
	
	/**
	 * 用户详情
	 * @author 刘新
	 * 
	 */
	public function loadDetail()
	{
		$id = I('id', '', '/^\d+$/');
		!$id && $this->error('参数错误');
		$this->assign('_title', '用户信息');
		$this->assign('id', $id);
		$this->assign('user', $user);
		$this->display('user_info');
	}
	
	/**
	 * 查询用户基本信息
	 * @author 刘新
	 */
	public function userInfo()
	{
		$id = I('id', '', '/^\d+$/');
		!$id && $this->error('请输入要查询的用户id');
		
		$type = I('type', '', '/^\d$/');
		!$type && $this->error('请输入要查询的信息类型');
		
		$return = array();
		$tpl = '';
		//查询用户基本信息
		if($type === '1') {
			$tpl = 'general';
			$return = $this->userGeneral($id);
		//查询用户详细信息
		} else if($type === '2') {
			$tpl = 'detail';
			$return = $this->userDetail($id);
		} else if($type === '3') {
			$tpl = 'bank';
			$return = $this->userBank($id);
		}
		
		if($return['error'] === 0) {
			$this->assign('user', $return['info']);
			$str = $this->fetch($tpl);
			$return['info'] = $str;
			$this->ajaxReturn($return);
		}
		
		$this->ajaxReturn($return);
	}
	
	/**
	 * 基本信息
	 * @param int|string $id
	 */
	private function userGeneral($id)
	{
		$user = $this->returnOne('User', array('id' => $id));
		if(!$user) {
			$return = array('error' => 1, 'info' => '用户基本查询失败');
		} else {
			$user['status_text'] = C('APP_USER')[$user['status']];
			
			//实名认证
			$user['realname_auth'] = '未认证';
			if($user['bit_status'] & 1) $user['realname_auth'] = '已认证';
			
			//合格认证
			$user['conforms_auth'] = '未认证';
			if($user['bit_status'] & 128) $user['conforms_auth'] = '已认证';
			
			unset($user['login_pwd']);
			unset($user['trade_pwd']);
			$return = array('error' => 0, 'info' => $user);
		}
		
		return $return;
	}
	
	/**
	 * 查询详细信息
	 * @param int|string $id
	 */
	private function userDetail($id)
	{
		$user = $this->returnOne('UserDetail', array('user_id' => $id));
		if($user === false) {
			$return = array('error' => 1, 'info' => '用户详情查询失败');
		} else if(!$user) {
			$return = array('error' => 1, 'info' => '该用户没有完善详细信息');
		} else {
			$user['status_text'] = C('APP_USER')[$user['status']];
			$user['sex_text'] = C('SEX')[$user['sex']];
			if($user['birthday']) $user['birthday_format'] = date('Y-m-d', $user['birthday']);
			
			$return = array('error' => 0, 'info' => $user);
		}
		//$this->ajaxReturn($return);
		return $return;
	}

	/**
	 * 查询用户绑定的银行卡信息
	 * @param int|string $id
	 */
	private function userBank($id)
	{
		$bankVerification = M("bankVerification");
		$user = $bankVerification->where(array("user_id"=>$id))->select();
		if($user === false) {
			$return = array('error' => 1, 'info' => '用户银行认证查询失败');
		} else if(!$user) {
			$return = array('error' => 1, 'info' => '该用户没有用户银行认证信息');
		} else {
			foreach($user as $key=>$val){
				if($val['status'] == '1'){
					$user[$key]['status_value'] = "未验证";
				}elseif($val['status'] == '2'){
					$user[$key]['status_value'] = "已验证通过";
				}
			}
			$return = array('error' => 0, 'info' => $user);
		}
		//$this->ajaxReturn($return);
		return $return;
		//return array('error' => 1, 'info' => '此功能待完善');
	}
	
	/**
	 * 编辑用户
	 * @author 刘新
	 */
	public function loadEditUser()
	{
		$id = I('id', '', '/^\d+$/');
		
		if(IS_AJAX) {
			if(!$id) $this->ajaxReturn(array('error' => 1, 'info' => '请输入要编辑的用户ID'));
			$type = I('type', '', '/^\d$/');
			if(!$type) $this->ajaxReturn(array('error' => 1, 'info' => '请输入要编辑的信息类型'));
			
			//查询实名认证信息
			if($type === '1') {
				$tpl = 'auth_realname';
				$logType = 'REALNAME';
				$bitStatus = 1;

				//查询用户详细信息
			} else if($type === '2') {
				$tpl = 'auth_conforms';
				$logType = 'CONFORMS';
				$bitStatus = 128;

			} else if($type === '3') {
				$tpl = 'auth_initiator';
				$logType = 'INITIATOR';
				$bitStatus = 4;
			}
			
			//查询
			$user = $this->returnOne('User', array('id' => $id), '', 'id,mobile,bit_status');
			
			//判断查询结果
			if(!$user) {
				$return = array('error' => 1, 'info' => '用户信息查询失败');
			} else {
				$user['is_auth'] = false;
				if($user['bit_status'] & $bitStatus) $user['is_auth'] = true;
					
				//查询日志
				$log = $this->returnList('AdminLog', array('target_id' => $id, 'type' => C('ADMIN_LOG_TYPE')[$logType]));
				$user['log'] = array();
				if($log) $user['log'] = $log;
				
				//渲染视图
				$this->assign('user', $user);
				$str = $this->fetch($tpl);
				
				$return = array('error' => 0, 'info' => $str);
			}
			
			$this->ajaxReturn($return);
		}
		
		//非AJAX请求
		!$id && $this->error('请输入要编辑的用户id');
		$user = $this->returnOne('User', array('id' => $id));
		if(!$user) $this->error('用户信息查询失败');
		
		$this->assign('_title', '编辑用户信息');
		$this->assign('user', $user);
		$this->display('edit');
	}
	
	/**
	 * 后台进行合格认证管理
	 * @param int|string $id
	 */
	public function conformsAuth()
	{
		$id = I('id', '', '/^\d+$/');
		if(!$id) $this->ajaxReturn(array('error'=>1, 'info'=>'请输入要编辑用户的ID'));
		$content = I('note', '');
		if(!$content) $this->ajaxReturn(array('error'=>1, 'info'=>'请输入标记说明'));
		
		$type = I('type', '', '/^[1-2]$/');
		if(!$type) $this->ajaxReturn(array('error'=>1, 'info'=>'参数错误'));
		
		//TODO:其它验证信息待完善
		
		$userModel = M('User');
		$userModel->startTrans();
		
		try {
			$user = $this->returnOne($userModel, array('id' => $id), '', 'id,mobile,bit_status');
			if(!$user) throw new \Exception('用户信息查询失败');
			
			if($type === '1') {
				if($user['bit_status'] & 128) throw new \Exception('该用户已通过合格认证');
				$bitStatus  = $user['bit_status'] ^ 128;
				$content = '合格投资人认证：' . $content;
			} else if($type === '2') {
				if(!($user['bit_status'] & 128)) throw new \Exception('该用户已经取消合格认证');
				$bitStatus  = $user['bit_status'] ^ 128;
				$content = '取消合格投资人认证：' . $content;
			}
			
			//修改认证
			$res = $userModel->where(array('id' => $id))->save(array('bit_status' => $bitStatus));
			if(!$res) throw new \Exception('操作失败');
			
			//日志
			$ldata['target_id'] = $id;
			$ldata['content'] = $content;
			$ldata['create_time'] = NOW_TIME;
			$ldata['update_time'] = NOW_TIME;
			$ldata['status'] = 1;
			$ldata['type'] = C('ADMIN_LOG_TYPE')['CONFORMS'];
			$admin = session('user_auth');
			$ldata['admin_id'] = $admin['uid'];
			$ldata['admin_name'] = $admin['username'];
			$res = M('AdminLog')->add($ldata);
			if(!$res) throw new \Exception('日志记录失败');
			
			//提交事务
			$return = array('error' => 0, 'info' => '操作成功');
			$userModel->commit();
		} catch (\Exception $e) {
			$userModel->rollback();
			$return = array('error' => 1, 'info' => $e->getMessage());
		}
		
		$this->ajaxReturn($return);
	}
	/**
	 * 更改状态
	 */
	public function changeStatus(){
		$method  = $_GET['method'];
		$id = I('id');
		$id = implode(",",$id);
		$userModel = M('User');
		$map['id']  = array('in',$id);
		if($method == "resume"){//启用
			$res = $userModel->where($map)->save(array('status' => '1'));
		}elseif($method=='forbid'){//禁用
			$res = $userModel->where($map)->save(array('status' => '0'));
		}elseif($method == "delete"){
			$res = $userModel->where($map)->delete();
		}
		$return = array('error' => 0, 'info' => '操作成功');
		$this->ajaxReturn($return);
	}
	/**
	 * 后台进行实名认证管理
	 * @param int|string $id
	 */
	public function realnameAuth()
	{
		$id = I('id', '', '/^\d+$/');
		if(!$id) $this->ajaxReturn(array('error'=>1, 'info'=>'请输入要编辑用户的ID'));
		$content = I('note', '');
		if(!$content) $this->ajaxReturn(array('error'=>1, 'info'=>'请输入标记说明'));
	
		$type = I('type', '', '/^[1-2]$/');
		if(!$type) $this->ajaxReturn(array('error'=>1, 'info'=>'参数错误'));
	
		//TODO:其它验证信息待完善
		
		$userModel = M('User');
		$userModel->startTrans();
	
		try {
			$user = $this->returnOne($userModel, array('id' => $id), '', 'id,mobile,bit_status');
			if(!$user) throw new \Exception('用户信息查询失败');
				
			if($type === '1') {
				if($user['bit_status'] & 1) throw new \Exception('该用户已通过实名认证');
				$bitStatus  = $user['bit_status'] ^ 1;
				$content = '实名认证：' . $content;
			} else if($type === '2') {
				if(!($user['bit_status'] & 1)) throw new \Exception('该用户已经取消实名认证');
				$bitStatus  = $user['bit_status'] ^ 1;
				$content = '取消实名认证：' . $content;
			}
				
			//修改认证
			$res = $userModel->where(array('id' => $id))->save(array('bit_status' => $bitStatus));
			if(!$res) throw new \Exception('操作失败');
				
			//日志
			$ldata['target_id'] = $id;
			$ldata['content'] = $content;
			$ldata['create_time'] = NOW_TIME;
			$ldata['update_time'] = NOW_TIME;
			$ldata['status'] = 1;
			$ldata['type'] = C('ADMIN_LOG_TYPE')['REALNAME'];
			$admin = session('user_auth');
			$ldata['admin_id'] = $admin['uid'];
			$ldata['admin_name'] = $admin['username'];
			$res = M('AdminLog')->add($ldata);
			if(!$res) throw new \Exception('日志记录失败');
				
			//提交事务
			$return = array('error' => 0, 'info' => '操作成功');
			$userModel->commit();
		} catch (\Exception $e) {
			$userModel->rollback();
			$return = array('error' => 1, 'info' => $e->getMessage());
		}
	
		$this->ajaxReturn($return);
	}
	
	/**
	 * 后台发起人管理
	 * @param int|string $id
	 */
	public function initiatorAuth()
	{
		$id = I('id', '', '/^\d+$/');
		if(!$id) $this->ajaxReturn(array('error'=>1, 'info'=>'请输入要编辑用户的ID'));
		$content = I('note', '');
		if(!$content) $this->ajaxReturn(array('error'=>1, 'info'=>'请输入标记说明'));
	
		$type = I('type', '', '/^[1-2]$/');
		if(!$type) $this->ajaxReturn(array('error'=>1, 'info'=>'参数错误'));
	
		//TODO:其它验证信息待完善
	
		$userModel = M('User');
		$userModel->startTrans();
	
		try {
			$user = $this->returnOne($userModel, array('id' => $id), '', 'id,mobile,bit_status');
			if(!$user) throw new \Exception('用户信息查询失败');
	
			if($type === '1') {
				if($user['bit_status'] & 4) throw new \Exception('该用户已通过发起人认证');
				$bitStatus  = $user['bit_status'] ^ 4;
				$content = '发起人认证：' . $content;
			} else if($type === '2') {
				if(!($user['bit_status'] & 4)) throw new \Exception('该用户已经取消发起人认证');
				$bitStatus  = $user['bit_status'] ^ 4;
				$content = '取消发起人认证：' . $content;
			}
	
			//修改认证
			$res = $userModel->where(array('id' => $id))->save(array('bit_status' => $bitStatus));
			if(!$res) throw new \Exception('操作失败');
	
			//日志
			$ldata['target_id'] = $id;
			$ldata['content'] = $content;
			$ldata['create_time'] = NOW_TIME;
			$ldata['update_time'] = NOW_TIME;
			$ldata['status'] = 1;
			$ldata['type'] = C('ADMIN_LOG_TYPE')['INITIATOR'];
			$admin = session('user_auth');
			$ldata['admin_id'] = $admin['uid'];
			$ldata['admin_name'] = $admin['username'];
			$res = M('AdminLog')->add($ldata);
			if(!$res) throw new \Exception('日志记录失败');
	
			//提交事务
			$return = array('error' => 0, 'info' => '操作成功');
			$userModel->commit();
		} catch (\Exception $e) {
			$userModel->rollback();
			$return = array('error' => 1, 'info' => $e->getMessage());
		}
	
		$this->ajaxReturn($return);
	}
}